<template>
  <div class="h-full flex overflow-hidden">
    <a-card
      class="mr-2"
      :class="treeExpand ? 'w-[320px]' : 'w-[55px]'"
      :body-style="{ height: '100%', display: 'flex', flexDirection: 'column', padding: '8px' }"
    >
      <BaseTitle :title="treeExpand ? '患者病历' : ''">
        <a-button type="primary" size="small" @click="() => (treeExpand = !treeExpand)">
          <BaseIcon v-if="treeExpand" name="DoubleLeftOutlined" />
          <BaseIcon v-else name="DoubleRightOutlined" />
        </a-button>
      </BaseTitle>
      <div v-if="!treeExpand" class="font-bold text-center">病历</div>
      <PatientsEmrTree v-show="treeExpand" ref="patientsTreeRef" class="flex-1" :emr-loading="emrLoading" can-edit @select="onSelectPatientsEmr" />
    </a-card>
    <div class="flex-1 mt-2 overflow-y-hidden overflow-x-auto">
      <div class="w-full flex flex-col h-full">
        <a-form :model="formState" class="px-4">
          <a-form-item label="初步诊断">
            <div class="flex w-full">
              <SelectTable v-model:value="formState.bcLczdZdmc" type="诊断" :custom-input="diagnosisCode" @select="onSelectTable($event)" @clear="onClear" />
              <a-radio-group
                v-model:value="formState.bcYblb"
                :disabled="formState.isCommit === 1"
                class="flex items-center ml-4"
                name="radioGroup"
                @change="onSaveMedical()"
              >
                <a-radio value="OU">OU</a-radio>
                <a-radio value="OD">OD</a-radio>
                <a-radio value="OS">OS</a-radio>
              </a-radio-group>
              <a-space class="flex justify-around ml-8">
                <a-button disabled type="default" @click="onSavePatientsEmr()">提取</a-button>
                <a-button :disabled="!store.currentEMR.id" type="primary" @click="onSavePatientsEmr()">保存</a-button>
                <a-button :disabled="!store.currentEMR.id" type="primary" ghost @click="onPrintEmr"><BaseIcon name="PrinterOutlined" />打印</a-button>
                <a-button v-if="currentEmrInfo.status === '1'" :disabled="!isShowEmr" type="primary" danger @click="onSubmitEmr('0')">撤审</a-button>
                <a-button v-else :disabled="!isShowEmr" type="primary" ghost @click="onSubmitEmr('1')">审核</a-button>
              </a-space>
            </div>
          </a-form-item>
          <a-form-item label="其他诊断">
            <div class="flex w-full">
              <SelectTable v-model:value="formState.bcQtzdZdmc" multiple type="诊断" @select="onSelectTableMultiple($event)" />
            </div>
          </a-form-item>
        </a-form>
        <a-spin :spinning="emrLoading" tip="初始化中..." wrapper-class-name="flex-1 overflow-auto">
          <div class="flex justify-center h-full overflow-hidden">
            <div class="w-28 mt-20 text-center text-base ml-8" :class="store.currentEMR.id ? '' : 'disabled-style'">
              <a-button type="text" @click="onInsert('处置')">处置</a-button>
              <a-divider class="my-4" />
              <a-button type="text" disabled @click="onInsert('检查')">检查</a-button>
              <a-divider class="my-4" />
              <a-button type="text" @click="onInsert('检验')">检验</a-button>
              <a-divider class="my-4" />
              <a-button type="text" @click="onInsert('西成药')">西成药</a-button>
              <a-divider class="my-4" />
              <a-button type="text" @click="onInsert('中草药')">中草药</a-button>
              <a-divider class="my-4" />
              <a-button type="text" @click="onInsert('手术')">手术</a-button>
              <a-divider class="my-4" />
              <a-button type="text" @click="eyesOpen = true">屈光检查</a-button>
              <a-divider class="my-4" />
            </div>
            <div class="relative w-[810px] min-h-[980px] overflow-auto template-status rounded" :class="isShowEmr ? '' : 'border'">
              <div
                v-show="isShowEmr"
                id="myWriterControl"
                dctype="WriterControlForWASM"
                contentrendermode="NormalHtmlEditable"
                workspacebackcolorstring="#DEDEDE"
                useclassattribute="true"
                heightcompress="true"
                backgroundtextoutputmode="None"
                imagedataembedinhtml="true"
                HeaderFooterEditable="true"
                pixelpagespacing="5"
                clientcontextmenutype="Custom"
                usedcwriterminijs="True"
                showdebuginfo="false"
                registercodeindex="0"
              >
                正在加载...
              </div>
              <a-empty v-show="!isShowEmr" description="请选择病历" />
            </div>
          </div>
        </a-spin>
      </div>
    </div>
    <InsertModal v-model:open="insertOpen" :type="insertType" @ok="onInsertOk" />
    <EyesModal v-model:open="eyesOpen" @ok="onEyesOk" />

    <!-- <a-card class="ml-2 w-[320px]" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column', padding: '8px' }">
      <div class="flex justify-around mb-4">
        <a-button :disabled="!isShowEmr" type="primary" @click="onSavePatientsEmr">保存</a-button>
        <a-button :disabled="!isShowEmr" type="primary" ghost><BaseIcon name="PrinterOutlined" />打印</a-button>
        <a-button v-if="currentEmrInfo.status === '1'" :disabled="!isShowEmr" type="primary" danger @click="onSubmitEmr(0)">撤审</a-button>
        <a-button v-else :disabled="!isShowEmr" type="primary" @click="onSubmitEmr(1)">审核</a-button>
      </div>

    </a-card> -->
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { getSystemConfig } from '@/utils/systemConfig'
import useUserStore from '@/store/user'
import cofirmModal from '@/utils/confirm.js'
import useStore from '@/views/out-doctor/store.js'
import InsertModal from './components/InsertModal'
import EyesModal from './components/EyesModal'
import PatientsEmrTree from './components/PatientsEmrTree.vue'

const store = useStore()

const { empId } = useUserStore()
const isShowEmr = ref(false)
const treeExpand = ref(true)

const formState = ref({})
const emrLoading = ref(true)
const state = reactive({
  ctl: null,
  props: {}
})

// 加载电子病历
const loadScript = () => {
  return new Promise((resolve) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://www.dcwriter.cn:8099/ServicePage.aspx?wasmres=dcwriter5.js'
    script.onload = () => resolve()
    document.head.insertBefore(script, null)
  })
}
//选择模板
watch(
  () => store.emrTemplateInfo,
  (info) => {
    info.id && onSelectTemplateEmr(info)
  }
)
//选择患者病历
const onSelectPatientsEmr = () => {
  if (store.currentEMR.id) {
    getEmrXml(store.currentEMR.id)
    setTimeout(() => {
      store.currentEMR.status === '1' && addStatusDom()
    }, 800)
  }
}
const currentEmrInfo = ref({})
// 根据模版id获取模版
const onSelectTemplateEmr = async (templateData) => {
  store.currentEMR = {}
  if (!templateData?.id) return
  store.currentEMR = { ...templateData, status: '', id: '' }
  store.emrTemplateDebounceClick && onSavePatientsEmr()
  const ctl = document.getElementById('myWriterControl')
  const { data, code, msg } = await post('/emr/patientEmrDocument/doInitEmrDocument', {
    brId: store.currentPatient.brId,
    jzbh: store.currentPatient.jzbh,
    categroyType: templateData.categroyType,
    templateId: templateData.id
  })
  if (code !== 0) return message.error(msg)
  isShowEmr.value = true
  if (!data) return (isShowEmr.value = false)
  try {
    ctl.LoadDocumentFromString(data)
  } catch (error) {
    console.error('🏳️‍🌈 <输出> 解析xml错误:', error)
  }
  state.ctl = ctl
}
const onSavePatientsEmr = async () => {
  if (store.currentEMR.categoryType === 0 && store.currentEMR.id !== store.outDoctorEmrId) {
    const isConfirm = await cofirmModal({ title: '提示', content: '门诊病历已存在是否覆盖保存?' })
    if (isConfirm) {
      await patientsTreeRef.value.onDeleteTemplate(store.outDoctorEmrId, false)
      onSavePatientsEmrFetch()
    }
  } else {
    onSavePatientsEmrFetch()
  }
}

const patientsTreeRef = ref(null)
const onSavePatientsEmrFetch = async () => {
  const ctl = document.getElementById('myWriterControl')
  const resultToString = ctl.XMLTextForSave

  const { code, msg, data } = await post('/emr/patientEmrDocument/savePatientEmrDocument', {
    brId: store.currentPatient.brId,
    categroyId: store.currentEMR.categroyId || store.currentEMR.parentId,
    id: store.currentEMR?.id,
    documentFileName: store.currentEMR.templateName,
    templateId: store.currentEMR.templateId,
    xml: resultToString,
    lsh: store.currentPatient.jzbh,
    categroyType: store.currentEMR.categroyType
  })
  if (code !== 0) return message.error(msg)
  message.success('保存成功')
  store.currentEMR = data
  patientsTreeRef.value.getTree()
  getEmrXml(data.id)
}
//审核
const onSubmitEmr = async (type) => {
  const { code, msg } = await post('/emr/emrDocumentFile/doChangeEmrTempleteAndCategoryStatus', {
    brId: store.currentPatient.brId,
    categroyId: store.currentEMR.categroyId || store.currentEMR.parentId,
    categroyType: store.currentEMR.categroyType,
    id: store.currentEMR?.id,
    templateId: store.currentEMR.templateId,
    status: type
  })
  if (code !== 0) return message.error(msg)
  message.success('操作成功')
  await patientsTreeRef.value.getTree()
  store.currentEMR.status = type
  type === '1' ? addStatusDom() : (document.querySelector('.template-status .status-icon').style.display = 'none')
}

const getCaseData = async () => {
  const { code, msg, data } = await post('/outp/mzys/getOutpRecordInfo', {
    mzjlbh: store.currentPatient.jzbh
  })
  if (code !== 0) return message.error(msg || '获取病历信息失败')
  formState.value = data
  // if (formState.value?.bcLczdZdmc) {
  //   isHasDiagnosis.value = true
  // } else {
  //   isHasDiagnosis.value = false
  // }
}
const mrmCode = ref('')
const getMrmCode = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId })
  if (res.code !== 0) return message.error(res.msg)
  mrmCode.value = res.data && res.data.blmb
}

const getEmrXml = async (id) => {
  const ctl = document.getElementById('myWriterControl')
  if (!ctl) return message.warning('电子病历加载中')
  const { data, code, msg } = await post('/emr/patientEmrDocument/getPatientEmrDocument', {
    id
  })
  if (code !== 0) return message.error(msg)
  if (data) {
    isShowEmr.value = true
  } else {
    isShowEmr.value = false
  }
  ctl.LoadDocumentFromString(data)
  state.ctl = ctl
}
const addStatusDom = () => {
  const dom = document.querySelector('.template-status div[dctype="page-container"]')
  if (!dom) return
  //添加角标
  const span = document.createElement('span')
  span.style.position = 'absolute'
  span.style.width = '36px'
  span.style.height = '36px'
  span.style.top = '5px'
  span.style.right = '9px'
  span.className = 'status-icon'
  span.style.backgroundImage =
    'url()'
  dom.appendChild(span)
}
const onPrintEmr = () => {
  const ctl = document.getElementById('myWriterControl')
  ctl.PrintDocument()
}
// const onAddKeyWord = async () => {
//   if (!newKeyWord.value) return message.warning('请输入关键词')
//   const { code, msg } = await post('/emr/emrCommonPhrases/doSaveEmrCommonPhrase', {
//     content: newKeyWord.value,
//     outOrder: orderKeyWord.value
//   })
//   if (code !== 0) return message.error(msg)
//   message.success('新增成功')
//   isShowAddKeyWord.value = false
//   orderKeyWord.value = null
//   newKeyWord.value = ''
//   getKeyWords()
// }
// const onDeleteKeyWord = async (item) => {
//   const { code, msg } = await post('/emr/emrCommonPhrases/doDelEmrCommonPhrase/' + item.id)
//   if (code !== 0) return message.error(msg)
//   message.success('删除成功')
//   getKeyWords()
// }
// const onSelectKeyWord = (item) => {
//   const ctl = document.getElementById('myWriterControl')
//   ctl.DCExecuteCommand('Spechars', false, item.content) //插入纯文本
// }
const eyesOpen = ref(false)

const onInsertOk = (word) => {
  const ctl = document.getElementById('myWriterControl')
  ctl.DCExecuteCommand('Spechars', false, word) //插入纯文本
  insertOpen.value = false
}
onMounted(async () => {
  getMrmCode()
  getCaseData()
  await loadScript()
  const ctl = document.getElementById('myWriterControl')
  if (window.CreateWriterControlForWASM) {
    window.CreateWriterControlForWASM(ctl)
  }

  window.WriterControl_OnLoad = () => {
    emrLoading.value = false
    onSelectTemplateEmr()
  }
  setTimeout(() => {
    emrLoading.value = false
  }, 2000)
  // emrLoading.value = false
})
const insertOpen = ref(false)
const insertType = ref('处置')
const onInsert = (type) => {
  insertOpen.value = true
  insertType.value = type
}
const diagnosisCode = getSystemConfig('OUTP_ALLOW_INPUT_ICD10') === '1' // 门诊允许输入诊断 0不允许，1允许
const onClear = () => {
  if (formState.value.bcLczdZdmc && formState.value.bcLczdZddm !== 'ICD10_INPUT') {
    formState.value.bcLczdZddm = ''
  } else {
    if (formState.value.bcLczdZdmc) {
      formState.value.bcLczdZddm = 'ICD10_INPUT'
    } else {
      formState.value.bcLczdZddm = ''
    }
  }
}
const onSelectTable = (select) => {
  formState.value.bcLczdZddm = select.zddm
  formState.value.bcLczdZdmc = select.zdmc
  formState.value.bcLczdIcd10Code = select.nmiIcd10Code
  formState.value.bcLczdIcd10Name = select.nmiIcd10Name
  store.currentMedical.bcLczdZddm = select.zddm
  store.currentMedical.bcLczdZdmc = select.zdmc
  onSaveMedical()
}
const onSelectTableMultiple = (select) => {
  formState.value['bcQtzdZdmc'] = formState.value['bcQtzdZdmc'] ? formState.value['bcQtzdZdmc'] + '，' + select.zdmc || select.mc : select.zdmc || select.mc
  formState.value['bcQtzdZddm'] = formState.value['bcQtzdZddm'] ? formState.value['bcQtzdZddm'] + '，' + select.zddm || select.dm : select.zddm || select.dm
  formState.value['bcLczdIcd10Name'] = formState.value['bcLczdIcd10Name']
    ? formState.value['bcLczdIcd10Name'] + '，' + select.nmiIcd10Name
    : select.nmiIcd10Name
  formState.value['bcLczdIcd10Code'] = formState.value['bcLczdIcd10Code']
    ? formState.value['bcLczdIcd10Code'] + '，' + select.nmiIcd10Code
    : select.nmiIcd10Code
  onSaveMedical()
}

// 保存诊断
const onSaveMedical = async () => {
  // 如果允许输入，要判断用户是选中的还是输入的 bcLczdZddm
  if (diagnosisCode) {
    if (!formState.value?.bcLczdZddm && formState.value?.bcLczdZdmc) {
      formState.value.bcLczdZddm = 'ICD10_INPUT'
    }
  }
  const res = await post('outp/mzys/doSavePatientEMR', {
    ...formState.value,
    brId: store.currentPatient.brId,
    jzbh: store.currentPatient.jzbh,
    mrmCode: mrmCode.value,
    qtzdxx: '',
    isCxtj: undefined,
    isCommit: undefined
  })
  const ctl = document.getElementById('myWriterControl')
  // 根据ID进行电子病历赋值
  ctl.SetElementTextByID('OM01.0020', formState.value.bcLczdZdmc)
  ctl.SetElementTextByID('IN02.0016', formState.value.bcQtzdZdmc)
  if (res.code !== 0) return message.error(res.msg)
}
const onEyesOk = (data, type) => {
  const ctl = document.getElementById('myWriterControl')
  // ctl.SetElementTextByID('OM01.0020', data)
  const obj = {
    file: data, //xml文档
    format: 'xml', //xml文档格式
    base64: 'false', //是否是base64字符串
    type: 'two',
    position: 'start'
  }
  type === 'od' && ctl.InsertXmlById(obj, 'OR01.0349', true)
  type === 'os' && ctl.InsertXmlById(obj, 'OR01.0350', true)
  eyesOpen.value = false
}
</script>
<style scoped lang="less">
.template-status-no {
  .status-icon {
    display: none;
  }
}
</style>
